package org.example.springmvc.filter;

import org.springframework.web.filter.CharacterEncodingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: DynamicResourceEncodingFilter
 * Package: org.example.springmvc.filter
 * Description:
 *
 * @Author wanghao
 * @Create 2024-07-11 15:59
 * @Version 1.0
 */
public class DynamicResourceEncodingFilter extends CharacterEncodingFilter {


    /**
     * 用于处理请求和响应字符编码
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String encoding = getEncoding();
        if (encoding != null) {
            if (this.isForceRequestEncoding() || request.getCharacterEncoding() == null) {
                request.setCharacterEncoding(encoding);
            }
            if (this.isForceResponseEncoding()) {
                //if (!request.getServletPath().toLowerCase().endsWith(".html")) {
                    response.setCharacterEncoding(encoding);
                //}
            }
        }
        filterChain.doFilter(request, response);
    }
}
